<?php

namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreOrderCancelController extends ClientController
{

    public function index()
    {

        $all = $this->all;
        $eo_id = $all['eo_id'];

        try {
            DB::beginTransaction();

            // 验证订单状态
            $order = DB::table('explore_order')->where('eo_id', '=', $eo_id)->lockForUpdate()->first();
            $order = json_decode(json_encode($order), true);

            // 工单数统计
            $works = DB::table('explore_work')
                ->where('eo_id', '=', $eo_id)
                ->lockForUpdate()
                ->count();

            // 查询探店使用余量
            $remaining = DB::table('explore_remaining')
                ->where('we_id', '=', $order['we_id'])
                ->where('channel_id', '=', $order['channel_id'])
                ->lockForUpdate()
                ->first();
            $remaining = json_decode(json_encode($remaining), true);

            if (!$order['status'] === Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING) {
                DB::rollBack();
                return $this->setReturnJson(-1, '订单状态已更新');
            }
            if ($works) {
                DB::rollBack();
                return $this->setReturnJson(-1, '订单已被达人接单，请联系客服处理');
            }
            if ($remaining['in_use_times'] < $order['total_num']) {
                DB::rollBack();
                Log::emergency('取消订单：订单数量异常' . ExploreOrderCancelController::class, ['order' => $order, 'remaining' => $remaining]);
                throw new \Exception('数量异常');
            }

            // 取消订单
            DB::table('explore_order')->where('eo_id', '=', $eo_id)->update([
                'status' => Data::DATA_DB_EXPLORE_ORDER_STATUS_FAILED,
            ]);

            // 退回余额
            DB::table('explore_remaining')
                ->where('we_id', '=', $order['we_id'])
                ->where('channel_id', '=', $order['channel_id'])
                ->increment('remaining_times', $order['total_num']);
            DB::table('explore_remaining')
                ->where('we_id', '=', $order['we_id'])
                ->where('channel_id', '=', $order['channel_id'])
                ->decrement('in_use_times', $order['total_num']);

            // 记录日志
            DB::table('explore_remaining_log')
                ->insert([
                    'r_id' => $remaining['r_id'],
                    'action' => Data::DATA_DB_EXPLORE_REMAINING_LOG_TYPE_ORDER_CANCEL,
                    'action_num' => $order['total_num'],
                    'rest_num' => $remaining['remaining_times'] + $order['total_num'],
                    'in_use_num' => $remaining['in_use_times'] - $order['total_num'],
                ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ExploreOrderCancelController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '订单异常，请联系客服处理');
        }
        DB::commit();
        return $this->setReturnJson(0, '取消成功');
    }

}
